package com.wtwd.campus.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zdl
 * @Description
 * @create 2021-07-01 17:21
 */
public class ObjectConvertUtil {
    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sources, Class<T> target) {
        if (sources == null) {
            return null;
        }
        List targetList = new ArrayList<>(sources.size());
        sources.forEach(source -> {
            T targetObject = null;
            try {
                targetObject = target.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
                return;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return;
            }
            BeanUtils.copyProperties(source, targetObject);
            targetList.add(targetObject);

        });
        return targetList;
    }
}
